package com.javasm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.javasm.domain.LoginUser;
import com.javasm.domain.User;
import com.javasm.mapper.MenuMapper;
import com.javasm.mapper.UserMapper;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @Author：MoDebing
 * @Version：1.0
 * @Date：2022-09-01-17:05
 * @Description: 登录的时候会进行用户登录验证和授权
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    private final UserMapper userMapper;

    private final MenuMapper menuMapper;

    public UserDetailsServiceImpl(UserMapper userMapper, MenuMapper menuMapper) {
        this.userMapper = userMapper;
        this.menuMapper = menuMapper;
    }

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        // 查询用户信息
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName,userName);
        User user = userMapper.selectOne(queryWrapper);

        // 如果没有查询到用户，就抛出异常,在认证的过程中抛出异常都会被安全框架捕获到
        if (Objects.isNull(user)){
            throw new RuntimeException("用户名或者密码错误");
        }

        //List<String> permissions = new ArrayList<>(Arrays.asList("test","admin","normal"));

        List<String> selectPerm = menuMapper.selectPerm(user.getId());

        // 把数据封装成 UserDetails对象进行返回
        return new LoginUser(user,selectPerm);
    }
}
